﻿/// <reference path="Meres.js" />

relationshipDiagram = function (options) {
    var me = this;
    var rdData = undefined;
    var engine = undefined;
    installjQueryPlugin();

    function installjQueryPlugin() {
        $(".relationshipDiagram .personSelector").personSelector(
        {
            selectedChanged: function () { },
            allowDragPerson: true

        });

        $('.relationshipDiagram').layout({
            center: {
                onresize: "innerLayout.resizeAll"
            }
        });

        var layout = $('.relationshipDiagram .innerLayout').layout({
            center: {
                onresize: "innerLayout.resizeAll"
            }
        });
        layout.sizePane("north", "28");

        $('.relationshipDiagram .tools').accordion({ fillSpace: true });

        renderActionBar(
            {
                target: '.relationshipDiagram .actionBar',
                commands: ["add", "clone", "delete"],
                viewModes: ["listView", "detailRdView"],
                viewModeSelected: function (event, ui) {
                    destroyDetailViewLayout();

                    if ($(ui.selected).hasClass('listView')) {
                        openListView();
                        return;
                    }

                    if ($(ui.selected).hasClass('detailRdView')) {
                        
                        openDetailRd(selRowId);
                        return;
                    }
                }
            });



        $('#newRd').click(function () {
            me.createDiagram();
        });

        $('#delRd').click(function () {
            if (selRdId == undefined)
                return;
            doAjax('/Meres/RelationshipDiagram/DeleteRelationDiagram', function () {
                selRdId = undefined;
                openListView();
            }, "rdId=" + selRdId);
        });
    }

    function destroyDetailViewLayout() {
        if (detailLayout == undefined)
            return;
        detailLayout.destroy();
        detailLayout = undefined;
    }

    var detailLayout = undefined;
    function installjQueryPlugginDetailView() {
        layout = $('.relationshipDiagram .mainContent').layout({
            center: {
                onresize: "innerLayout.resizeAll"
            }
        });
        layout.sizePane("east", "150");
        layout.sizePane("south", "30");
        detailLayout = layout;

        $('.relationshipDiagram .zoomSlider').slider();

        $('.relationshipDiagram .selectable').selectable();

        $('.toggleShowHide').click(function () {
            var $this = $(this);
            var onClass = "toggleOn";
            var offClass = "toggleOff";
            var on = $this.hasClass('toggleOn');
            if (on) {
                $this.removeClass(onClass);
                $this.addClass(offClass);
                $this.attr('value', 'Show');
            }
            else {
                $this.removeClass(offClass);
                $this.addClass(onClass);
                $this.attr('value', 'Hide');
            }
            layout.toggle("east");
        });

        $('#rdDrawer').droppable({
            drop: function (event, ui) {
                var txt = ui.draggable[0].innerText;
                var pId = $(ui.draggable[0]).attr('data-personid');

                var offset1 = { x: ui.offset.left, y: ui.offset.top };
                var offset2 = { x: $('#rdDrawer').offset().left, y: $('#rdDrawer').offset().top };
                var pos = { x: offset1.x - offset2.x, y: offset1.y - offset2.y };

                engine.createNode({ x: pos.x, y: pos.y, text: txt, data: { pId: pId, hash: Utils.guid() } });
            }
        });

    }

    function openDetailRd(rdId) {
        doAjax("/Meres/RelationshipDiagram/GetDetailViewNew?rdId=" + rdId, function (evt) {
            var $content = $('.relationshipDiagram .mainContent');
            $content.html(evt.Html);
            setupDrawer();
            installjQueryPlugginDetailView();
            selRdId = rdId;
            setRdData(evt.ViewModel);
        });
    }

    var selRdId = undefined;

    function openListView() {
        var $content = $('.relationshipDiagram .mainContent');
        $content.html('<table id="rdList"></table><div id="rdListPager" />');
        $("#rdList").jqGrid({
            url: '/Meres/RelationshipDiagram/GetRdDataListJson',
            datatype: "json",
            mtype: "POST",
            colNames: ["Id", "Name", "NodeCount", "LinkCount", "Owners", "Participants", "UpdateTime"],
            colModel: [
                            { name: "Id", index: "Id", width: 30, align: "center", vertical: "middle" },
                            { name: "Name", index: "Name", width: 100, align: "left", editable: true, classes: 'jqGridSelCol' },
                            { name: "NodeCount", index: "NodeCount", width: 100, align: "center" },
                            { name: "LinkCount", index: "LinkCount", width: 100, align: "center" },
                            { name: "Participants", index: "Participants", width: 100, align: "left" },
                            { name: "Owners", index: "OwnersText", width: 100, align: "left" },
                            { name: "UpdateTime", index: "UpdateTime", width: 100, align: "left", editable: true, sorttype: "date", formatoptions: { newformat: 'd.m.Y' }, formatter: 'date' }],
            // Grid total width and height
            width: $content.width() - 2,
            height: $content.height() - 70 - 2,

            // Paging                    
            pager: $("#rdListPager"),
            rowNum: 10,
            rowList: [5, 10, 20],
            viewrecords: true,
            // Default sorting
            sortname: "Id",
            sortorder: "asc",

            // Grid caption
            caption: "RD LIST",

            serializeRowData: function (postData) {
                var d = postData.ModifiedDate;
                postData.ModifiedDate = '11/28/1984';
                return postData;
            },

            onCellSelect: function (rowId, iCol, cellcontent, e) {
                selRowId = rowId;
                if (iCol != 1)
                    return;

                JsUtil.selectSelectableElements($(".relationshipDiagram .viewMode"), $(".relationshipDiagram .viewMode").children()[1]);

            },

            editurl: '/Meres/RelationshipDiagram/EditRelationDiagram'

        }).navGrid("#rdListPager",
                    {
                        refresh: true, add: true, edit: true, del: true
                    },
                    {}, // settings for edit
                    {}, // settings for add
                    {}, // settings for delete
                    { sopt: ["cn"] } // Search options. Some options can be set on column level
                 );


        $("#rdList").jqGrid('navGrid', "#rdList", { edit: false, add: false, del: false });
        $("#rdList").jqGrid('inlineNav', "#rdList");
    }

    var selRowId = undefined;

    function setupDrawer() {
        $('#canvasContainer').html('<div id="rdDrawer" style="width:100%; height:100%"></div>');
        if (engine != undefined)
            engine.destroy();
        engine = new RdEngine('rdDrawer', {
            onElementCreating: function (evt) {
                var eType = evt.element.typeName;

                if (eType == 'NodeControlEx') {
                    var dat = {
                        "Graph.Id": rdData.Id,
                        Data: JSON.stringify({ "personId": evt.element.attrs.model.pId }),
                        CHash: evt.element.attrs.model.hash,
                        X: evt.element.x,
                        Y: evt.element.y,
                        H: evt.element.height,
                        W: evt.element.width
                    };

                    doAjax("/Meres/RelationshipDiagram/AddOrUpdateRdNodeJson", function (evt1) {
                        evt.element.attrs.model = evt1;
                        evt.success(evt1);
                        log("NodeAdded:" + evt1.Id);
                    }, dat);

                    return;
                }

                if (eType == 'ConnectorControlEx') {
                    var dat = {
                        "Graph.Id": rdData.Id,
                        Data: JSON.stringify({ LinkType: 'sample_type', Other: 'other data' }),
                        'LeftNode.Id': evt.element.node1.attrs.model.Id,
                        'RightNode.Id': evt.element.node2.attrs.model.Id
                    };

                    doAjax("/Meres/RelationshipDiagram/AddRdLinkJson", function (evt1) {
                        evt.element.attrs.model.data = evt1;
                        evt.success(evt1);
                        log("LinkAdded:" + evt1.Id);
                    }, dat);

                    return;
                }

                evt.success('ok');
            },
            onElementMouseUp: function (evt) {
                var pos = evt.rect.getAbsolutePosition();
                var id = evt.attrs.model.Id;
                var dat = { Id: id, X: pos.x, Y: pos.y, W: evt.width, H: evt.height };
                doAjax("/Meres/RelationshipDiagram/UpdateUiData", function (evt1) {
                    log("UiUpdated:" + id);
                }, dat, 'POST');
            },
            onElementRemoving: function (evt) {
                var eType = evt.element.typeName;
                var id = evt.element.attrs.model.Id;
                if (eType == 'ConnectorControlEx') {
                    doAjax("/Meres/RelationshipDiagram/DeleteRdLink?linkId=" + id, function (evt1) {
                        evt.success(evt1);
                        log("LinkDeleted:" + id);
                    });
                }
                else if (eType == 'NodeControlEx') {
                    doAjax("/Meres/RelationshipDiagram/DeleteRdNode?nodeId=" + id, function (evt1) {
                        evt.success(evt1);
                        log("NodeDeleted:" + id);
                    });
                }
            }
        });
    }

    function setRdData(rd) {
        rdData = rd;
        if (rdData == undefined)
            return;
        engine.setText("RD:" + rd.Name);

        for (var i = 0; i < rdData.Nodes.length; i++) {
            var n = rdData.Nodes[i];
            engine.addNode({ x: n.X, y: n.Y, text: n.PersonName, data: n });
        }

        for (var i = 0; i < rdData.Links.length; i++) {
            var node1 = undefined;
            var node2 = undefined;
            var nodes = engine.getNodes();
            var link = rdData.Links[i];
            for (var j = 0; j < nodes.length; j++) {
                if (nodes[j].attrs.model.Id == link.LeftNodeId)
                    node1 = nodes[j];
                else if (nodes[j].attrs.model.Id == link.RightNodeId)
                    node2 = nodes[j];
            }
            if (node1 == undefined || node2 == undefined)
                throw 'Cannot find nodes for link';
            engine.addConnector({ node1: node1, node2: node2, data: link });
        }

        engine.draw();
    }

    this.createOrOpenDefaultDiagram = function (personId) {
        // After success
    };

    this.createDiagram = function () {
        doAjax("/Meres/RelationshipDiagram/AddOrUpdateRdJson",
            function (evt) {
                openDetailRd(evt.Id);
            },
            { Name: 'TEST_RD' });
    };

    $($('.viewMode').children()[0]).select();

    JsUtil.selectSelectableElements($(".relationshipDiagram .viewMode"), $(".relationshipDiagram .viewMode").children()[0]);

}